import os
import json
import traceback

from flask import Flask
from flask import request, render_template
from werkzeug.exceptions import HTTPException

from database.UserDAO import User,UserDAO

app = Flask(__name__, template_folder="html")
app.config['DEBUG'] = True

# 404错误处理
@app.errorhandler(404)
def not_found_error(error):
    return render_template('404.html'), 404

# 500错误处理
@app.errorhandler(500)
def internal_error(error):
    # 获取错误的堆栈跟踪信息
    error_traceback = ''.join(traceback.format_exception(type(error), error, error.__traceback__))
    
    return render_template('500.html', error=error, error_traceback=error_traceback), 500

# 处理所有HTTP异常
@app.errorhandler(HTTPException)
def handle_http_exception(error):
    return render_template('error.html', error=error), error.code

# 处理所有未捕获的异常
@app.errorhandler(Exception)
def handle_exception(error):
    # 获取错误的堆栈跟踪信息
    error_traceback = ''.join(traceback.format_exception(type(error), error, error.__traceback__))
    
    return render_template('500.html', error=error, error_traceback=error_traceback), 500

@app.route("/")
def default():
    return render_template("index.html")

@app.route("/<page_name>.html")
def page(page_name):
    return render_template(f"{page_name}.html")

@app.route("/validate", methods=["GET", "POST"])
def validate():
    username_ = request.form.get("username")
    password_ = request.form.get("password")
    user_dao = UserDAO()
    if user_dao.checkUser(username_, password_):
        return "success"
    else:
        return "failed"

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8003, debug=True)